package cuishifeng.blog.learn.algorithm.排序算法.冒泡排序;

import cuishifeng.blog.learn.algorithm.TestData;

/**
 * 冒泡排序
 *
 * @author cuishifeng <cuishifeng0207@163.com>
 * Created on 2021-02-27
 */
public class BubbleSort {

    public static void main(String[] args) {
        int[] array = TestData.arrayData();
//        TestData.printArray(sort(array));
        TestData.printArray(sort2(array));
    }

    /**
     * 5 6 4 1 3 2
     *
     * @param array array
     */
    public static int[] sort(int[] array) {
        int range = array.length - 1;
        for (int i = 0; i < range; i++) {
            for (int j = 0; j < range - i; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
        return array;
    }

    /**
     * 5 6 4 1 3 2
     *
     * @param array array
     */
    public static int[] sort2(int[] array) {
        int range = array.length - 1;
        boolean swap = true;
        for (int i = 0; i < range; i++) {
            if (!swap) {
                break;
            }
            swap = false;
            for (int j = 0; j < range - i; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    swap = true;
                }
            }
        }
        return array;
    }
}
